package edu.henu.personnel.controller;

import com.github.pagehelper.PageInfo;
import edu.henu.personnel.entity.Catalog;
import edu.henu.personnel.entity.DownLoadFile;
import edu.henu.personnel.service.catalog.CatalogService;
import edu.henu.personnel.service.file.FileService;
import edu.henu.personnel.utils.DateUtil;
import edu.henu.personnel.utils.FileUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

/**
 * @program: PersonnelProject
 * @description: 下载中心控制器
 * @author: zhuyang
 * @create: 2019-05-25 14:19
 */

@Controller
public class DownloadController {

    @Autowired
    private CatalogService catalogService;

    @Autowired
    private FileService fileService;

    @GetMapping("/fileCatalogs")
    public String dflist(Model model) {
        List<Catalog> catalogList = catalogService.getCatalogInfoByMemo("下载中心");
        model.addAttribute("catalogs", catalogList);
        return "file/dclist";
    }

    @GetMapping("/files/{cid}")
    public String list(@PathVariable("cid") Integer cid,  Model model) {
        PageInfo<DownLoadFile> files = fileService.getFilesByCid(cid, 1);
        model.addAttribute("files", files);
        return "file/list";
    }

    @GetMapping("/toaddfile")
    public String toAddPage(Model model) {
        List<Catalog> catalogs = catalogService.getCatalogInfoByMemo("下载中心");
        model.addAttribute("catalogs", catalogs);
        return "file/add";
    }

    @PostMapping("/file")
    public String addFile(DownLoadFile file, @RequestParam("uploadfile") MultipartFile uploadfile) throws IOException {
        if (StringUtils.isBlank(file.getFname())) {
            file.setFname(uploadfile.getOriginalFilename());
        }

        String fileTargetPath = FileUtil.downloadFileUpload(uploadfile, FileUtil.filePath);
        file.setFpath(fileTargetPath);

        file.setFdate(DateUtil.getStoreDate());

        int result = fileService.addDownloadFile(file);

        return "redirect:/files/" + file.getFcid();
    }

    @DeleteMapping("/file/{fid}")
    public String removeFile(@PathVariable("fid") Integer fid) {
        int result = fileService.removeDownloadFile(fid);
        return "redirect:/fileCatalogs";
    }
}
